/*
 * @Description:
 * @Autor: fage
 * @Date: 2022-05-07 14:44:17
 * @LastEditors: fage
 * @LastEditTime: 2022-07-04 15:38:41
 */
const fs = require("fs");
const path = require("path");
const makeDir = require("make-dir");

module.exports = {
  getSliceInfoArr,
  readOneBlock,
  joinBlcoksToFile,
};

function getSliceInfoArr(filePath, blockSize = 10485760) {
  if (!fs.existsSync(filePath)) {
    return null;
  }
  const size = fs.statSync(filePath).size;
  let blockCount = parseInt(size / blockSize);
  blockCount = size % blockSize == 0 ? blockCount : blockCount + 1;
  const arr = [];
  for (let i = 0; i < blockCount; i++) {
    const o = {
      start: i * blockSize,
      end: (i + 1) * blockSize - 1,
    };
    if (o.end >= size - 1) {
      o.end = size - 1;
    }
    if (o.end >= o.start) {
      arr.push(o);
    }
  }
  return arr;
}
function readOneBlock(filePath, op) {
  return new Promise((resolve, reject) => {
    if (!fs.existsSync(filePath)) {
      return reject("file not found");
    }
    const reader = fs.createReadStream(filePath, op);
    const bufs = [];
    reader.on("data", (data) => {
      bufs.push(data);
    });
    reader.on("end", () => {
      resolve(Buffer.concat(bufs));
    });
  });
}
function joinBlcoksToFile(filePath, bufferArr) {
  return new Promise(async (resolve, reject) => {
    if (fs.existsSync(filePath)) {
      fs.unlinkSync(filePath);
    }
    const dir = path.dirname(filePath);
    await makeDir(dir);
    const writeStream = fs.createWriteStream(filePath);
    writeStream.on("error", (err) => {
      reject(err);
    });
    writeStream.on("finish", () => {
      resolve();
    });
    for (const buff of bufferArr) {
      writeStream.write(buff);
    }
    writeStream.end();
  });
}
